package leetcode_401_500;

public class LeeCode_402 {
    public static void main(String[] args) {
        System.out.println(removeKdigits("1432219", 3));
        System.out.println(removeKdigits("10200", 1));
        System.out.println(removeKdigits("10", 2));
        System.out.println(removeKdigits("1173", 2));
        System.out.println(removeKdigits("1234567890", 9));
    }
    private static String removeKdigits(String num, int k) {
        StringBuilder sb = new StringBuilder(num);
        int i = 0;
        while (i < sb.length() - 1){
            if (sb.charAt(i) > sb.charAt(i + 1)){
                sb.replace(i, i + 1,"");
                i--;
                i = Math.max(i, 0);
                k--;
                if (k == 0){
                    break;
                }
            }else {
                i++;
            }
        }
        if (k > 0){
            sb.replace(sb.length() - k, sb.length(), "");
        }
        while (sb.length() != 0 && sb.charAt(0) == '0'){
            sb.replace(0, 1, "");
        }
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
